<?php

namespace App\Http\Middleware;

use App\Services\PermissionService;
use Closure;
use Exception;

class PermissionCheck
{

    /**
     * @param $request
     * @param Closure $next
     * @return mixed
     * @throws Exception
     */
    public function handle($request, Closure $next)
    {
        /*访问需要的权限*/
        $needPermission = request()->route()->getAction('as');

        /*用户*/
        $user = $this->userByJwt();

        $permission = app(PermissionService::class)->findByField('name', $needPermission)->first();

        /*包含权限*/
        if($permission){
            /*判断用户是否拥有权限*/
            $userAllPermissions = $this->getUserAllPermissions($user);
            if($userAllPermissions->contains($permission)) {
                return $next($request);
            }else {
                /*抛出异常*/
                throw new Exception('用户无权限：' . $permission->name . '('.$permission->display_name.')', 2);
            }
        }

        return $next($request);
    }
}
